package org.mch.func.db.conn;

import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;

import org.mch.biz.ui.BizEvent;
import org.mch.comm.exec.MsgException;
import org.mch.func.cons.ConsDB;
import org.mch.start.MEnv;

public class ConnDBEvent extends BizEvent {
	private static final long serialVersionUID = 420252357552519442L;

	public ConnDBEvent(ConnDBPanel panel) {
		super(panel);
	}

	public ConnDBEvent() {
		super(null);
	}

	public void buttonClicked(MouseEvent e) throws Exception {
		if (e.getSource() == getPanel().getButton_conn()) {
			conn();
		} else {
			//
		}
	}

	public void conn() throws Exception {

		ConsDB.connInfo.setDbtype(getPanel().getComboBox_dbtype().getSelectedIndex());
		ConsDB.connInfo.setAddress((String) getPanel().getComboBox_dbaddress().getSelectedItem());
		ConsDB.connInfo.setPort_str((String) getPanel().getComboBox_dbport().getSelectedItem());
		ConsDB.connInfo.setDatabasename((String) getPanel().getComboBox_dbname().getSelectedItem());
		ConsDB.connInfo.setUsername((String) getPanel().getComboBox_username().getSelectedItem());
		ConsDB.connInfo.setPassword(new String(getPanel().getPasswordField().getPassword()));

		if ((ConsDB.conn != null) && (!ConsDB.conn.isClosed())) {
			ConsDB.conn.close();
		}

		ConsDB.conn = createConnection(ConsDB.connInfo);
		ConsDB.conn.getMetaData().getDatabaseProductName();

		ConsDB.dbmd = ConsDB.conn.getMetaData();

		MEnv.statusMsg("成功连接数据库：" + ConsDB.connInfo.getDatabasename());
	}

	public Connection createConnection(DBConnInfo para) throws Exception {
		checkJDBCConnPara(para);
		Class.forName(para.getDriver()).newInstance();
		return DriverManager.getConnection(para.getURL(), para.getUsername(), para.getPassword());
	}

	protected void checkJDBCConnPara(DBConnInfo infovo) throws Exception {
		if ((infovo.getAddress() == null) || (infovo.getAddress().trim().equals(""))) {
			throw new MsgException("数据库地址不能为空！");
		}
		if ((infovo.getPort_str() == null) || ((infovo.getPort_str().trim().equals("")) && (infovo.getDbtype() != 4))) {
			throw new MsgException("数据库端口不能为空！");
		}
		if ((infovo.getUsername() == null) || (infovo.getUsername().trim().equals(""))) {
			throw new MsgException("用户名不能为空！");
		}
		if (infovo.getPassword() == null) {
			infovo.setPassword("");
		}
		if ((infovo.getDatabasename() == null) || (infovo.getDatabasename().trim().equals("")))
			throw new MsgException("数据库名称不能为空！");
	}

	@Override
	public ConnDBPanel getPanel() {
		return (ConnDBPanel) super.getPanel();
	}
}